<template>
  正在登陆中……
</template>

<script>
import {defineComponent} from 'vue'
import {decode} from "urlencode";
import authApi from "@/utils/api/authApi";
import {closeToast, showFailToast, showLoadingToast, showNotify, showSuccessToast} from "vant";
import 'vant/es/toast/style';
export default defineComponent({
  name: "LoginCode",
  created() {
    let from = this.$route.query.state
    if(from){
      this.from = decode(from)
    }
    this.checkLogin()
  },
  data(){
    return {

    }
  },
  methods: {
    async checkLogin(){
      let userId = await authApi.checkLogin()
      if(userId !== null){
        this.backFrom()
      }else {
        this.loginByCode()
      }
    },
    async loginByCode(){
      let code = this.$route.query.code
      try {
        showLoadingToast({
          message: '登录中...',
          forbidClick: true,
          duration: 0
        });
        let userId = await authApi.loginByCode(code)
        showSuccessToast('登录成功')
        this.backFrom()
      }catch (data){
        switch (data.code){
          case 1:
            showFailToast({
              message: '登录授权失败，请退出重试'
            })
            break
        }
      }finally {

      }
    },
    backFrom(){
      if(this.from){
        window.open(this.from,'_self')
      }else {
        window.open('/index')
      }
    }
  },
})
</script>


<style scoped lang="less">

</style>